<template>
	<view>
		<!-- 自动定位（县级）与手动搜索（到村） -->
		<view class="px-[24rpx] py-[20rpx]">
			<view class="flex items-center justify-between">
				<view class="text-[28rpx] text-[#333]">自动定位（县级）</view>
				<view @click="autoLocateCounty" class="text-[26rpx] text-[#1677ff]">定位</view>
			</view>
			<view v-if="locating" class="text-[24rpx] text-[#888] mt-[8rpx]">正在定位…</view>
			<view v-if="locationError" class="text-[24rpx] text-[#e64a19] mt-[8rpx]">{{ locationError }}</view>
		</view>

		<view class="px-[24rpx] pb-[10rpx]">
			<u-input v-model="query" placeholder="输入村/镇/街道等关键字" clearable @input="onQueryInput" />
			<view v-if="suggestions.length" class="mt-[10rpx] bg-[#fff] rounded-[8rpx] overflow-hidden">
				<view v-for="item in suggestions" :key="item.id" class="py-[16rpx] px-[8rpx] border-b border-[#f0f0f0]" @click="selectSuggestion(item)">
					<view class="text-[28rpx] text-[#333]">{{ item.title }}</view>
					<view class="text-[24rpx] text-[#888] mt-[6rpx]">{{ item.address }}</view>
				</view>
			</view>
		</view>

		<!-- 地图展示（APP优先使用原生地图） -->
		<view class="px-[24rpx] pb-[10rpx]">
			<!-- #ifdef APP-PLUS -->
			<view class="flex items-center justify-between mb-[10rpx]">
				<view class="text-[26rpx] text-[#333]">地图</view>
				<view @click="openChooseLocation" class="text-[26rpx] text-[#1677ff]">打开地图选点</view>
			</view>
			<!-- #endif -->
			<map
				style="width: 100%; height: 400rpx;"
				:latitude="mapLat"
				:longitude="mapLng"
				:markers="markers"
				:show-location="true"
			></map>
		</view>

		<city-select
			@cityClick="cityClick"
			:formatName="formatName"
			:activeCity="activeCity"
			:hotCity="hotCity"
			:obtainCitys="obtainCitys"
			:isSearch="true"
			ref="citys"
		></city-select>
	</view>
</template>

<script>
import citys from './citys.js'
import provinces from '@/uni_modules/vk-uview-ui/libs/address/provinces.json'
import cityList from '@/uni_modules/vk-uview-ui/libs/address/citys.json'
import areas from '@/uni_modules/vk-uview-ui/libs/address/areas.json'
import citySelect from '@/components/city-select/city-select.vue'
export default {
	data() {
		return {
			//需要构建索引参数的名称（注意：传递的对象里面必须要有这个名称的参数）
			formatName: 'title',
			//当前城市
			activeCity: {
				id: 0,
				title: '...'
			},
			//热门城市
			hotCity: [
				
			],
			//显示的城市数据
			obtainCitys: [
				
			],
			// 定位与搜索
			locating: false,
			locationError: '',
			query: '',
			suggestions: [],
			amapKey: '3f4d4c2a39784c2ebfd48a8078068c6a', // 请替换为你的高德地图 key
			queryTimer: null,
			// 地图状态
			mapLat: 39.909187,
			mapLng: 116.397451,
			markers: []
		}
	},
	components: {
		citySelect
	},
	onLoad() {
		//动态更新数据
		setTimeout(() => {
			//修改数据格式
			this.formatName = 'cityName'
			//修改当前城市
			// this.activeCity = {
			// 	cityName: '乌鲁木齐市',
			// 	cityCode: 650100
			// }
			const selectCity = uni.getStorageSync("selectCity");
			if(selectCity){
				this.activeCity = selectCity;
			}			
			
			//修改热门城市
			this.hotCity = [
				{
					cityName: '北京',
					cityCode: 110100
				},
				{
					cityName: '上海',
					cityCode: 310100
				},
				{
					cityName: '广州',
					cityCode: 440100
				},
				{
					cityName: '深圳',
					cityCode: 440300
				},
				{
					cityName: '天津',
					cityCode: 120100
				},
				{
					cityName: '南京',
					cityCode: 320100
				},
				{
					cityName: '杭州',
					cityCode: 330100
				},
				{
					cityName: '武汉',
					cityCode: 420100
				},
				{
					cityName: '郑州',
					cityCode: 410100
				},
				{
					cityName: '成都',
					cityCode: 510100
				}
			]
			//修改构建索引数据
			this.obtainCitys = citys
			// uni.showToast({
			// 	icon: 'none',
			// 	title: '更新数据成功',
			// 	// #ifdef MP-WEIXIN
			// 	duration: 3000,
			// 	// #endif
			// 	mask: true
			// })
		}, 1000)
	},
	methods: {
		// 自动定位到县级
		autoLocateCounty() {
			this.locationError = ''
			this.locating = true
			
			// #ifdef APP-PLUS
			// APP 平台下，先检查定位权限
			plus.geolocation.getCurrentPosition(
				(position) => {
					const { latitude, longitude } = position.coords
					this.handleLocationSuccess(latitude, longitude)
				},
				(error) => {
					console.error('定位失败:', error)
					let errorMsg = '未授权或无法获取定位'
					if (error.code === 1) {
						errorMsg = '定位权限被拒绝，请在设置中开启定位权限'
						// 引导用户去设置
						uni.showModal({
							title: '定位权限',
							content: '需要定位权限才能使用此功能，是否前往设置开启？',
							success: (res) => {
								if (res.confirm) {
									plus.runtime.openURL('app-settings:')
								}
							}
						})
					} else if (error.code === 2) {
						errorMsg = '定位失败，请检查GPS是否开启'
					} else if (error.code === 3) {
						errorMsg = '定位超时，请稍后重试'
					}
					this.locationError = errorMsg
					this.locating = false
				},
				{
					enableHighAccuracy: true,
					timeout: 10000,
					maximumAge: 0
				}
			)
			// #endif
			
			// #ifndef APP-PLUS
			// 非 APP 平台使用 uni.getLocation
			uni.getLocation({
				type: 'gcj02',
				geocode: false,
				altitude: false,
				success: (pos) => {
					const { latitude, longitude } = pos
					this.handleLocationSuccess(latitude, longitude)
				},
				fail: (err) => {
					console.error('定位失败:', err)
					let errorMsg = '未授权或无法获取定位'
					if (err.errMsg && err.errMsg.includes('auth deny')) {
						errorMsg = '定位权限被拒绝，请在设置中开启定位权限'
					} else if (err.errMsg && err.errMsg.includes('timeout')) {
						errorMsg = '定位超时，请稍后重试'
					}
					this.locationError = errorMsg
					this.locating = false
				}
			})
			// #endif
		},
		
		// 处理定位成功后的逆地理编码
		handleLocationSuccess(latitude, longitude) {
			// 高德地图逆地理编码 API（注意：高德地图使用 经度,纬度 格式）
			uni.request({
				url: `https://restapi.amap.com/v3/geocode/regeo?key=${this.amapKey}&location=${longitude},${latitude}&extensions=all`,
				method: 'GET',
				success: (res) => {
					try {
						if (res.data.status !== '1' || !res.data.regeocode) {
							throw new Error(res.data.info || '逆地理编码失败')
						}
						const r = res.data.regeocode
						const comp = r.addressComponent || {}
						const provinceName = comp.province || ''
						const cityName = comp.city || ''
						const districtName = comp.district || ''

						const mapped = this.mapRegionToCodes(provinceName, cityName, districtName)
						const data = {
							cityCode: mapped.areaCode || mapped.cityCode,
							cityName: mapped.areaName || mapped.cityName,
							provinceName,
							provinceCode: mapped.provinceCode,
							cityLevelName: mapped.cityName,
							cityLevelCode: mapped.cityCode,
							districtName: mapped.areaName,
							districtCode: mapped.areaCode,
							lat: latitude,
							lng: longitude,
							address: r.formatted_address || ''
						}
						uni.$emit("selectCity", data)
						uni.setStorageSync("selectCity", data)
						this.activeCity = data
						this.locating = false
						uni.navigateBack({ delta: 1 })
					} catch (e) {
						this.locationError = '定位解析失败: ' + (e.message || '未知错误')
						this.locating = false
					}
				},
				fail: (err) => {
					console.error('逆地理编码失败:', err)
					this.locationError = '定位服务不可用'
					this.locating = false
				}
			})
		},

		// 通过坐标更新地图和标记
		updateMap(lat, lng) {
			this.mapLat = lat
			this.mapLng = lng
			this.markers = [{ id: 1, latitude: lat, longitude: lng }]
		},

		// 将省/市/区名称映射到编码
		mapRegionToCodes(provinceName, cityName, districtName) {
			let provinceIndex = provinces.findIndex(p => p.name === provinceName)
			if (provinceIndex < 0) {
				provinceIndex = provinces.findIndex(p => provinceName.includes(p.name.slice(0,2)))
			}
			const provinceCode = provinces[provinceIndex]?.code || ''
			const cityArr = cityList[provinceIndex] || []
			let cityIndex = cityArr.findIndex(c => c.name === cityName)
			if (cityIndex < 0) cityIndex = cityArr.findIndex(c => cityName.includes(c.name.replace('市','')))
			const cityCode = cityArr[cityIndex]?.code || ''
			const areaArr = (areas[provinceIndex] && areas[provinceIndex][cityIndex]) ? areas[provinceIndex][cityIndex] : []
			let areaIndex = areaArr.findIndex(a => a.name === districtName)
			if (areaIndex < 0) areaIndex = areaArr.findIndex(a => districtName.includes(a.name.replace('区','').replace('县','')))
			const areaCode = areaArr[areaIndex]?.code || ''
			return {
				provinceCode,
				cityCode,
				cityName: cityArr[cityIndex]?.name || cityName,
				areaCode,
				areaName: areaArr[areaIndex]?.name || districtName
			}
		},

		// 搜索输入（联想到村/镇）
		onQueryInput(val) {
			if (this.queryTimer) clearTimeout(this.queryTimer)
			this.queryTimer = setTimeout(() => {
				this.fetchSuggestions(val)
			}, 300)
		},
		fetchSuggestions(keyword) {
			const q = (keyword || '').trim()
			if (!q) { this.suggestions = []; return }
			// 高德地图搜索建议 API
			uni.request({
				url: `https://restapi.amap.com/v3/place/text?key=${this.amapKey}&keywords=${encodeURIComponent(q)}&city=全国&extensions=all`,
				method: 'GET',
				success: (res) => {
					if (res.data.status === '1' && res.data.pois) {
						const data = res.data.pois || []
						this.suggestions = data.map((d, i) => ({
							id: d.id || i,
							title: d.name,
							address: d.address || d.pname + d.cityname + d.adname,
							location: {
								lat: parseFloat(d.location.split(',')[1]),
								lng: parseFloat(d.location.split(',')[0])
							}
						}))
					} else {
						this.suggestions = []
					}
				},
				fail: () => {
					this.suggestions = []
				}
			})
		},
		// 选择联想项后，逆地理到县/村信息并写入
		selectSuggestion(item) {
			const { lat, lng } = item.location || {}
			if (lat == null || lng == null) return
			// 高德地图逆地理编码 API（注意：高德地图使用 经度,纬度 格式）
			uni.request({
				url: `https://restapi.amap.com/v3/geocode/regeo?key=${this.amapKey}&location=${lng},${lat}&extensions=all`,
				method: 'GET',
				success: (res) => {
					if (res.data.status === '1' && res.data.regeocode) {
						const r = res.data.regeocode
						const comp = r.addressComponent || {}
						const mapped = this.mapRegionToCodes(comp.province, comp.city, comp.district)
						this.updateMap(lat, lng)
						const data = {
							cityCode: mapped.areaCode || mapped.cityCode,
							cityName: mapped.areaName || mapped.cityName,
							provinceName: comp.province,
							provinceCode: mapped.provinceCode,
							cityLevelName: mapped.cityName,
							cityLevelCode: mapped.cityCode,
							districtName: mapped.areaName,
							districtCode: mapped.areaCode,
							lat,
							lng,
							address: r.formatted_address || '',
							town: comp.township || '',
							placeTitle: item.title
						}
						uni.$emit("selectCity", data)
						uni.setStorageSync("selectCity", data)
						this.activeCity = data
						uni.navigateBack({ delta: 1 })
					}
				}
			})
		},

		// 原生选择地点（APP）
		openChooseLocation() {
			// #ifdef APP-PLUS
			uni.chooseLocation({
				success: (res) => {
					const { latitude, longitude, name, address } = res
					this.updateMap(latitude, longitude)
					// 高德地图逆地理解析到县级（注意：高德地图使用 经度,纬度 格式）
					uni.request({
						url: `https://restapi.amap.com/v3/geocode/regeo?key=${this.amapKey}&location=${longitude},${latitude}&extensions=all`,
						method: 'GET',
						success: (r) => {
							if (r.data.status === '1' && r.data.regeocode) {
								const result = r.data.regeocode
								const comp = result.addressComponent || {}
								const mapped = this.mapRegionToCodes(comp.province, comp.city, comp.district)
								const data = {
									cityCode: mapped.areaCode || mapped.cityCode,
									cityName: mapped.areaName || mapped.cityName,
									provinceName: comp.province,
									provinceCode: mapped.provinceCode,
									cityLevelName: mapped.cityName,
									cityLevelCode: mapped.cityCode,
									districtName: mapped.areaName,
									districtCode: mapped.areaCode,
									lat: latitude,
									lng: longitude,
									address: address || result.formatted_address || '',
									placeTitle: name || ''
								}
								uni.$emit("selectCity", data)
								uni.setStorageSync("selectCity", data)
								this.activeCity = data
								uni.navigateBack({ delta: 1 })
							}
						}
					})
				}
			})
			// #endif
		},
		cityClick(item) {
			// uni.showToast({
			// 	icon: 'none',
			// 	title: 'item: ' + JSON.stringify(item),
			// 	// #ifdef MP-WEIXIN
			// 	duration: 3000,
			// 	// #endif
			// 	mask: true
			// })
			
			const data = {
				cityCode: item.cityCode,
				cityName: item.cityName
			}		
			uni.$emit("selectCity",data);
			uni.setStorageSync("selectCity",data);
			uni.navigateBack({
				delta: 1
			})			
		}
	}
}
</script>

<style></style>
